<template>
    <div class="couponCenter">
      <ul v-if="listData">
        <li ref="refList" v-for="(item,index) in listData" :class="['storeCoupon', 'type'+item.couponType,  item.status == '3' ? 'allover' : '']">
          <a class="getCoupon" :data-coupontype="item.coupontype" href="javascript:;" data-listingid="" :data-bid="item.batchId" 
          data-counponnum="15" data-counponcount="1000">
            <div  :class="'block clearfix type'+ item.couponType"
                :style="returnImage(item.couponWallShowImgURL, item.couponType)">
                <div class="coupon">
                  <div class="info">
                    <div class="desText"><span class="quan_name"></span><p>{{item.listingName}}</p></div>
                    <p><span>￥</span><big>6.66</big>
                      <i class="discount">{{item.fullCutAmount ? '不限金额使用' : '满'+ item.fullCutAmount +'可用'}}</i>
                      </p>
                  </div>
                </div>
                <div class="coudate"><i class="bor_m"></i>
                  <div class="info" @click="goUse(item)" v-if=" item.status=='3'">
                    <span class="valid btn" >去使用</span>
                  </div>
                  <div class="info" @click="receiveCoupon(item.batchId,index)" v-else>
                    <span class="valid btn">立即领取</span>
                  </div>
                </div>
            </div></a>
          </li>
      </ul>
      <div class="loading loadMore" v-show="!status"><img src="//i0.ulecdn.com/ulewap/i/loading1.gif" alt=""></div>
    </div>
</template>

<script>
/* eslint-disable */

import fetchJsonp from "../common/fetchJsonp";
import $ from "../common/uleUtil";
import {staticUrl,uleUrl} from '../common/env'
export default {
  name: "CouponList",
  props: ["cid"],
  page: "1",
  data() {
    return {
      userId: "10000025972",
      page: "1",
      status: true,
      reqFinish: true,
      listData: [],
      receiveData: {b9c459b6bcc95e81:true},
      msg: "Welcome to Your Vue.js App"
    };
  },
  watch: {
    cid: function() {
      this.page = 1;
      this.reqFinish = true;
      this.getContent();
    }
  },
  created() {
    this.getContent();
  },
  mounted() {
    let oThis = this;
     window.addEventListener('scroll',function(){  
                // 判断是否滚动到底部  
              let sT = document.documentElement.scrollTop || document.body.scrollTop;
                let wT = sT + window.innerHeight;
                if(document.body.scrollTop + window.innerHeight >= (document.body.offsetHeight) && oThis.status && oThis.reqFinish) {
                  let last = oThis.$refs.refList.length-1;
                  let lastliTop = oThis.$refs.refList[last] && oThis.$refs.refList[last].offsetTop;

                  if(wT >= lastliTop){
                    console.log(oThis.page)
                      oThis.page++;
                      oThis.getContent();
                  }
                  
                }
     })
  },
  methods: {
    goUse (item) {
      let oThis = this;
      let storeUrl = '//m.' + uleUrl + '/store/index/';
      let storeLen = item.storeId ? item.storeId.split(",").length : 0;
      let listIdLen = item.listingId ? item.listingId.split(",").length : 0;
      let url = '';
       if (item.couponType == 1 && storeLen > 1) { //店铺券对应多个店铺的时候
            url = '//www.' + uleUrl + '/ulewap/coupon_store_list.html?storeId=' + item.storeId;
        } else if (item.couponType == 2 && listIdLen > 1) { //商品券对应多个商品的时候
            url = '//www.' + uleUrl + '/ulewap/coupon_goods_list.html?batchId=' + item.batchId;
        } else if (item.couponType == 1) { //店铺券(一对一)
            if ($.browser.ule) {
                url = storeUrl + item.storeId + '_' + encodeURI(item.storeName);
            } else { //普通浏览器
                url = storeUrl + item.storeId;
            }
        } else if (item.couponType == 2) { //商品券(一对一)
            url = shopUrl + listingId;
        } else if (item.couponType == 3 || item.couponType == 5 || item.couponType == 6) { //运费券 //全场通用券 //品类券
            if ($.browser.ule) {
                url = 'ulemobile://uleHomepage';
            } else {
                url = '//m.' + uleUrl;
            }
        }
        location.href = url;
    },
    getContent: function() {
      const oThis = this;
      const index = this.cid;
      this.status = false;
      if (index == '10001') {
        var counponSort = "cw_serial_number_app asc";
        var counponShowType = "J";
      } else {
        var counponSort = "type desc,push_time desc";
        var counponShowType = "A";
      }

      var msg = {
        tabType: "1", // 区分app和PC端(必传:1) 是
        // type:1,//    优惠券展示渠道(0：商家券,1：邮乐券)，不传表示查所有    否
        channel: "All", // 展示渠道 Web：PC端展示 App：APP端展示 All：(都展示)必传   是
        categoryType: String(this.cid), //   优惠劵品类类型(值暂定)必传  是
        pageSize: "10", //    每页显示条数  否
        userOnlyid: oThis.userId,
        pageIndex: oThis.page, //    当前页数(从1开始)                 否
        //merTypeFlag:'0',
        //storeTypeFlag:'3',
        sort: counponSort, //排序
        showType: counponShowType //    展示类型: A:全量展示 S：单个店铺 P:手机端指定店铺查询（查某个店铺下所有的券）
      };
      fetchJsonp("//m."+uleUrl+"/mact/coupon/searchCoupon.do", msg,{jsonpCallback:'jsonCallback'})
        .then(function(response) {
          oThis.status = true;
          if (response.code === "0000") {
            
            if(oThis.page == '1') {
              //第一页
              oThis.listData = [];
              document.body.scrollTop = '0'
            }
            response.returnMsg.couponList.forEach(element => {
              oThis.listData.push(element)
            });
            if(oThis.page * 10 >= response.returnMsg.couponTotal) {
              //没有数据
              oThis.reqFinish = false;
              return false;
            }
            // oThis.listData = response.returnMsg;
          }
        })
        .catch(function(err) {
          console.log("Fetch错误:" + err);
        });
    },
    receiveCoupon (bId,index){
 
      let oThis = this;
      // $.isLogin(function(){
        oThis.receiveFunc(bId,index)
      // })
    },
    receiveFunc(bId,index) {
        let oThis = this;
        oThis.status = false;
        let msg =  {
              //batchId:args.bId,         //     批次号（加密 DESUtils工具类加密）
              batchId: decodeURIComponent(bId), //     批次号（加密 DESUtils工具类加密）
              receiveAddress:encodeURIComponent(location.href), //     领取地址
              //storeId:args.sId          //     店铺id
          }
        fetchJsonp("//merchant."+ uleUrl +"/ulecard/merchantCoupon/receive/ReceiveMerchantCoupon/receiveMSCouponDES", msg,{jsonpCallback:'jsonpcallbck',jsonpCallbackFunction:'jsonp4'})
        .then(function(response) {
          oThis.status = true;
          if(response.code == '0001'){
            //成功
            oThis.$set(oThis.listData[index],'status','3')
          } else if (response.code == '2013') { //优惠券已领完
            oThis.$set(oThis.listData[index],'status','3')
          } else if (response.code == '2014') { //领券张数已超过上限
            oThis.$set(oThis.listData[index],'status','3')
          }
           oThis.bus.$emit('tips',response.msg)
          
        })
        .then(function(json) {
          console.log('parsed json', json)
        }).catch(function(ex) {
          console.log('parsing failed', ex)
        })
    },
    returnImage(imgUrl, couponType){
      if(imgUrl && (couponType == '2' || couponType == '3')){
        return 'background-image:url('+ imgUrl +')';
      }
    }
  }
};
</script>

<style scoped>
.content .couponCenter div.block .coupon .info .desText{
  text-align: left;
}
.loading{
  display: block;
}
.content div .coupon .info > p {
  text-align: left;
}
.info p span {
  /* vertical-align: text-bottom; */
  font-size: 17px;
  /* margin-top: 17px; */
  position: absolute;
  left: 0;
  top: 2px;
}
.couponCenter .discount {
  max-width: 80px;
}
/*1店铺券*/
/*1、通用券 popular  ef514c*/
.content div.type5 .quan_name:after {
  content: '全场券';
}

.content div .coupon .info > p {
  color: #e42222;
  font-size: 0;
  font-family: tahoma,'SFUIText-Medium';
}
.content div .coupon .info > p span{
  color: #e42222;
}
.content div.block .coupon .info big{
   font-family: tahoma,'SFUIText-Medium';
}
.content div.type5 .coudate {
  background: #e42222;
}
.content div.block.flag5 .coudate .info .valid {
  color: #fff; /* background: #FFF; */
}
.content div.type5 {
  background: #fff url('../assets/quan.png')
    no-repeat 10px 10px;
  background-size: 91px;
}

/*2、话费券 bill  f87412*/
.content div.type4 .coudate {
  background: #3fa7f6;
}
.content div.type4 .quan_name {
  background: #3fa7f6;
}
.content div.type4 {
  background: #fff url('../assets/chong.png')
    no-repeat 10px 10px;
  background-size: 91px;
}
.content div.type4 .quan_name:after {
  content: '充值券';
}

/*3、运费券 freight  4fc1da*/

.content div.type3 .coudate {
  background: #41b25a;
}
.content div.type3 .quan_name {
  background: #41b25a;
}
.content div.type3 .quan_name:after {
  content: '运费券';
}
.content div.type3 {
  background: #fff url('../assets/yun.png') no-repeat 10px 10px;
  background-size: 91px;
}

/*4、品类券 category  daa757*/
.content div.type6 .quan_name:after {
  content: '品类券';
}
.content div.type6 .coudate {
  background: #bd44fb;
}
.content div.type6 .quan_name {
  background: #bd44fb;
}
.content div.block.flag6 .coudate .info .valid {
  color: #daa757;
  background: #fff;
}
.content div.type6 {
  background: #fff url('../assets/ping.png')
    no-repeat 10px 10px;
  background-size: 91px;
}

/*5、店铺券 shop  59a9e6*/
.content div.type1 .quan_name:after {
  content: '店铺券';
}
.content div.type1 .coudate {
  background: #e42222;
}
.content div.block.flag1 .coudate .info .valid {
  color: #fff; /* background: #FFF; */
}
/*6、商品券 commodity  6ebd86*/
.content div.type2 .quan_name:after {
  content: '商品券';
}
.content div.type2 .coudate {
  background: #f6730b;
}
.content div.type2 .quan_name {
  background: #f67308;
}
.content div.block.flag2 .coudate .info .valid {
  color: #fff; /* background: #FFF; */
}
</style>
